package top.hzy520.dao;

import top.hzy520.DButil.DButil;
import top.hzy520.dto.UserStateDto;
import top.hzy520.entity.UserState;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class UserStateDaoImpl implements UserStateDao {
    @Override
    public List<UserStateDto> findUserStateByUserid(Long userid) {
        Connection conn=null;
        PreparedStatement stm=null;
        SimpleDateFormat formatyear=new SimpleDateFormat("yyyy-MM-dd");
        DateFormat format = new  SimpleDateFormat("HH:mm:ss");
        formatyear = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.MEDIUM);
        try {
            String sql="SELECT * FROM userstate WHERE userid=?";
            conn=DButil.initConnection();
           stm=conn.prepareStatement(sql);
           stm.setLong(1,userid);
           ResultSet resultSet=stm.executeQuery();
          List<UserStateDto> userStateList=new ArrayList<>();
           while (resultSet.next()){
               UserStateDto userState=new UserStateDto();
               userState.setUserid(resultSet.getLong("userid"));
               userState.setLogintime(format.format(resultSet.getTime("logintime")));
               userState.setLogindate(formatyear.format(resultSet.getDate("logindate")));
               userState.setLogouttime(format.format(resultSet.getTime("logouttime")));
               userState.setLogoutdate(formatyear.format(resultSet.getDate("logoutdate")));
               userState.setState(resultSet.getInt("state"));
               userStateList.add(userState);
           }
           return userStateList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
